import store from '@/store'
import router from '@/router'
import { parseTime } from '@/utils/duojuhe'
import { saveChatUsersChatList } from '@/api/chat/im/chatList'

const KEY_INDEX_NAME = 'send_message_index_name'

/**
 * 通过对话索引查找对话列表下标
 *
 * @param {String} indexName
 */
export function findTalkIndex(indexName) {
  return store.state.talks.items.findIndex(
    item => item.indexName == indexName
  )
}

/**
 * 通过对话索引查找对话列表
 *
 * @param {String} indexName
 */
export function findTalk(indexName) {
  return store.state.talks.items.find(item => item.indexName == indexName)
}

/**
 * 格式化聊天对话列表数据
 *
 * @param {Object} params
 */
export function formateTalkItem(params) {
  let options = {
    id: 0,
    talkType: 1,
    receiverId: 0,
    realName: '未设置昵称',
    friendRemark: '',
    headPortrait: '',
    isDisturb: 0,
    isTop: 0,
    isOnline: 0,
    unreadNum: 0,
    content: '......',
    draftText: '',
    msgText: '',
    indexName: '',
    createTime: parseTime(new Date()),
  }

  Object.assign(options, params)
  options.indexName = `${options.talkType}_${options.receiverId}`

  return options
}

/**
 * 打开指定对话窗口
 *
 * @param {Integer} talkType 对话类型[1:私聊;2:群聊;]
 * @param {Integer} receiverId 接收者ID
 */
export function toTalk(talkType, receiverId) {
  saveChatUsersChatList({
    talkType:talkType,
    receiverId:receiverId,
  }).then(({ code, data }) => {
      sessionStorage.setItem(KEY_INDEX_NAME, `${talkType}_${receiverId}`)
      router.push({
        path: '/imChatAdmin/myImChatList',
        query: {
          v: new Date().getTime(),
        },
      })
  })
}

/**
 * 获取需要打开的对话索引值
 *
 * @returns
 */
export function getCacheIndexName() {
  let indexName = sessionStorage.getItem(KEY_INDEX_NAME)
  if (indexName) {
    sessionStorage.removeItem(KEY_INDEX_NAME)
  }

  return indexName
}
